import 'package:country_code_picker/country_code_picker.dart';
import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/address_model.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/custom_text_field.dart';

import 'package:efood_multivendor/view/screens/auth/widget/code_picker_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:phone_number/phone_number.dart';

import '../../../../controller/localization_controller.dart';

class DeliveryInformationBottomSheet extends StatefulWidget {
  final Function(AddressModel, String, String, String, String) onOkPressed;
  final bool callOnArrval;

  DeliveryInformationBottomSheet(
      {required this.onOkPressed, this.callOnArrval = false});

  @override
  State<DeliveryInformationBottomSheet> createState() =>
      _DeliveryInformationBottomSheetState();
}

class _DeliveryInformationBottomSheetState
    extends State<DeliveryInformationBottomSheet> {
  final FocusNode _nameFocus = FocusNode();

  final FocusNode _referralCodeFocus = FocusNode();
  final FocusNode _alternativePhoneFocus = FocusNode();

  final TextEditingController _nameController = TextEditingController();

  final TextEditingController _alternativePhoneController =
      TextEditingController();
  final TextEditingController _referralCodeController = TextEditingController();
  TextEditingController _inputAddressController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool editLocation = false;
  bool addAlternativePhone = false;
  String? _countryDialCode;
  bool isValid = false;
  bool isReferralEditable = false;

  @override
  void initState() {
    _countryDialCode =
        Get.find<AuthController>().getUserCountryCode().isNotEmpty
            ? Get.find<AuthController>().getUserCountryCode()
            : CountryCode.fromCountryCode(
                    Get.find<SplashController>().configModel!.country!)
                .dialCode;
    isReferralEditable =
        Get.find<UserController>().userInfoModel?.isReferralCodeEditable ==
            true;
    super.initState();
  }

  String removeCountryCode(String phoneNumber) {
    // Check if the phone number starts with '+251'
    if (phoneNumber.startsWith('+251')) {
      // Remove the first occurrence of '+251'
      return phoneNumber.replaceFirst('+251', '');
    }
    // Return the original phone number if it doesn't start with '+251'
    return phoneNumber;
  }

  @override
  Widget build(BuildContext context) {
    _alternativePhoneController.text =
        Get.find<UserController>().userInfoModel?.alternativePhone != null
            ? removeCountryCode(
                Get.find<UserController>().userInfoModel!.alternativePhone!)
            : '';
    if (Get.find<UserController>().userInfoModel?.referredBy != null) {
      _referralCodeController.text =
          Get.find<UserController>().userInfoModel!.referredBy!;
    }

    return SingleChildScrollView(
      child: GetBuilder<LocationController>(builder: (locationController) {
        return Padding(
          padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
          child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(8.0),
                    topRight: Radius.circular(8.0)),
                color: Color.fromARGB(255, 252, 250, 250),
              ),
              padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
              child: Form(
                key: _formKey,
                child: Column(children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(),
                      InkWell(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Padding(
                          padding: EdgeInsets.only(
                              left: Dimensions.PADDING_SIZE_EXTRA_SMALL,
                              right: Dimensions.PADDING_SIZE_EXTRA_SMALL,
                              top: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                          child: Icon(Icons.close,
                              color: Theme.of(context).disabledColor),
                        ),
                      ),
                    ],
                  ),
                  Column(children: [
                    Padding(
                      padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                      child: Center(
                          child: Text(
                        'order_delivered_to'.tr,
                        style: sfMedium.copyWith(
                            fontSize: Dimensions.fontSizeSmall * 0.45.w,
                            fontWeight: FontWeight.w500),
                      )),
                    ),
                  ]),
                  SizedBox(
                    height: 2.h,
                  ),
                  Row(
                    children: [
                      Text(
                        'name'.tr,
                        style: sfRegular.copyWith(
                            fontSize: Dimensions.fontSizeDefault,
                            fontWeight: FontWeight.bold,
                            color: Theme.of(context).disabledColor),
                      ),
                    ],
                  ),
                  SizedBox(height: 1.h),
                  Row(
                    children: [
                      Expanded(
                        child: CustomTextField(
                          hintText:
                              Get.find<UserController>().userInfoModel?.fName ??
                                  '',
                          controller: _nameController,
                          focusNode: _nameFocus,
                          inputType: TextInputType.name,
                          capitalization: TextCapitalization.words,
                          divider: false,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 1.h),
                  Row(
                    children: [
                      Text(
                        'phone_number'.tr,
                        style: sfRegular.copyWith(
                            fontWeight: FontWeight.bold,
                            fontSize: Dimensions.fontSizeDefault,
                            color: Theme.of(context).disabledColor),
                      ),
                    ],
                  ),
                  SizedBox(height: 1.h),
                  Row(
                    children: [
                      Expanded(
                        child: CustomTextField(
                          hintText:
                              Get.find<UserController>().userInfoModel?.phone ??
                                  '',
                          inputType: TextInputType.name,
                          isEnabled: false,
                          capitalization: TextCapitalization.words,
                          divider: false,
                        ),
                      ),
                      TextButton(
                          onPressed: () {
                            setState(() {
                              addAlternativePhone = !addAlternativePhone;
                              _alternativePhoneFocus.requestFocus();
                            });
                          },
                          child: Text('+ ' + 'add'.tr,
                              style: TextStyle(
                                  color: Theme.of(context)
                                      .colorScheme
                                      .secondary))),
                    ],
                  ),
                  SizedBox(height: 1.h),
                  // SizedBox(height: 1.h),
                  addAlternativePhone
                      ? Row(
                          children: [
                            Text(
                              'alternative_phone'.tr,
                              style: sfRegular.copyWith(
                                  fontWeight: FontWeight.bold,
                                  fontSize: Dimensions.fontSizeDefault,
                                  color: Theme.of(context).disabledColor),
                            ),
                          ],
                        )
                      : SizedBox(),
                  SizedBox(height: 1.h),
                  addAlternativePhone
                      ? Container(
                          decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.circular(Dimensions.RADIUS_SMALL),
                            color: Theme.of(context).cardColor,
                          ),
                          child: Column(children: [
                            Row(children: [
                              CodePickerWidget(
                                alignLeft: true,
                                onChanged: (CountryCode countryCode) {
                                  setState(() {
                                    _countryDialCode = countryCode.dialCode;
                                  });
                                },
                                initialSelection: Get.find<SplashController>()
                                    .configModel
                                    ?.country,
                                favorite: [_countryDialCode!],
                                flagDecoration:
                                    BoxDecoration(shape: BoxShape.circle),
                                showCountryOnly: true,
                                padding: EdgeInsets.zero,
                                showDropDownButton: true,
                                backgroundColor: Colors.white,
                                flagWidth: 40,
                                hideMainText: true,
                                textStyle: sfRegular.copyWith(
                                  fontSize: Dimensions.fontSizeLarge,
                                  color: Theme.of(context)
                                      .textTheme
                                      .bodyMedium
                                      ?.color,
                                ),
                              ),
                              Center(
                                child: Text(
                                  _countryDialCode ?? '',
                                  style: TextStyle(
                                    fontSize: Dimensions.fontSizeDefault,
                                  ),
                                ),
                              ),
                              Expanded(
                                  flex: 10,
                                  child: CustomTextField(
                                    hintText: Get.find<UserController>()
                                            .userInfoModel
                                            ?.alternativePhone ??
                                        '',
                                    controller: _alternativePhoneController,
                                    focusNode: _alternativePhoneFocus,
                                    inputType: TextInputType.phone,
                                    divider: false,
                                    fontSize: Dimensions.fontSizeDefault,
                                  )),
                            ]),
                          ]))
                      : SizedBox(),
                  SizedBox(height: addAlternativePhone ? 1.h : 0),

                  Row(
                    children: [
                      Text(
                        !isReferralEditable
                            ? 'referral_code'.tr +
                                ' ' +
                                '(' +
                                'non_changeable'.tr +
                                ')'
                            : 'referral_code'.tr,
                        style: sfRegular.copyWith(
                            fontWeight: FontWeight.bold,
                            fontSize: Dimensions.fontSizeDefault,
                            color: Theme.of(context).disabledColor),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 1.h,
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: CustomTextField(
                          hintText: isReferralEditable == true
                              ? 'enter_referal'.tr
                              : Get.find<UserController>()
                                  .userInfoModel!
                                  .referredBy!,
                          controller: _referralCodeController,
                          focusNode: _referralCodeFocus,
                          inputType: TextInputType.text,
                          capitalization: TextCapitalization.words,
                          divider: false,
                          isEnabled: isReferralEditable,
                        ),
                      ),
                    ],
                  ),
                  // Row(
                  //   children: [
                  //     Text(
                  //       'delivery_address'.tr,
                  //       style: sfRegular.copyWith(
                  //           fontWeight: FontWeight.bold,
                  //           fontSize: Dimensions.fontSizeDefault,
                  //           color: Theme.of(context).disabledColor),
                  //     ),
                  //   ],
                  // ),
                  // SizedBox(
                  //   height: 1.h,
                  // ),
                  // Row(
                  //   children: [
                  //     Expanded(
                  //         child: AddressWidget(
                  //       address: locationController.getUserAddress(),
                  //       fromAddress: false,
                  //       fromCheckout: true,
                  //       fromSetting: true,
                  //     )),
                  //     TextButton(
                  //         onPressed: () {
                  //           try {
                  //             Navigator.push(
                  //               context,
                  //               MaterialPageRoute(
                  //                 builder: (context) => AddAddressScreen(
                  //                   address:
                  //                       locationController.getUserAddress(),
                  //                   // fromSignUp: false,
                  //                   // fromAddAddress: false,
                  //                   // canRoute: false,
                  //                   // route: 'checkout',
                  //                 ),
                  //               ),
                  //             );
                  //           } catch (e) {}
                  //         },
                  //         child: Text(
                  //           'change'.tr,
                  //           style: TextStyle(
                  //               color: Theme.of(context).colorScheme.secondary),
                  //         ))
                  //   ],
                  // ),
                  SizedBox(
                    height: 1.h,
                  ),
                  Container(
                    decoration: BoxDecoration(boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: Dimensions.PADDING_SIZE_SMALL,
                      )
                    ]),
                    child: TextFormField(
                      controller: _inputAddressController,
                      style: sfRegular.copyWith(),
                      validator: (value) {
                        if ((value == null || value.isEmpty) &&
                            widget.callOnArrval) {
                          return "Fill in the delivery address description";
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        hintText: 'new_address'.tr,
                        hintStyle: sfRegular.copyWith(
                            color: Theme.of(context).hintColor),
                        isDense: true,
                        filled: true,
                        fillColor: Theme.of(context).cardColor,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(
                                Get.find<LocalizationController>().isLtr
                                    ? 10
                                    : 0),
                          ),
                          borderSide: BorderSide.none,
                        ),
                        //contentPadding: EdgeInsets.only(top: 10, bottom: 10)
                      ),
                    ),
                  ),

                  SizedBox(
                    height: 4.h,
                  ),
                  SafeArea(
                    child: CustomButton(
                        buttonText: 'confirm_order'.tr,
                        onPressed: () async {
                          String _numberWithCountryCode = _countryDialCode! +
                              _alternativePhoneController.text.trim();
                          try {
                            if (GetPlatform.isAndroid) {
                              PhoneNumber phoneNumber = await PhoneNumberUtil()
                                  .parse(_numberWithCountryCode);
                              _numberWithCountryCode = '+' +
                                  phoneNumber.countryCode +
                                  phoneNumber.nationalNumber;
                              isValid = true;
                            } else {
                              if (_alternativePhoneController.text
                                          .trim()
                                          .length ==
                                      9 &&
                                  (_alternativePhoneController.text
                                          .trim()
                                          .startsWith('9') ||
                                      _alternativePhoneController.text
                                          .trim()
                                          .startsWith('7'))) {
                                isValid = true;
                              }
                            }
                          } catch (e) {}

                          if (_alternativePhoneController.text.isNotEmpty &&
                              !isValid) {
                            showCustomSnackBar(
                                'invalid_alternative_phone_number'.tr);
                          } else if (_formKey.currentState?.validate() ==
                              true) {
                            widget.onOkPressed(
                                locationController.getUserAddress()!,
                                _numberWithCountryCode,
                                _nameController.text.trim(),
                                _referralCodeController.text.trim(),
                                _inputAddressController.text.trim());
                          }
                        }),
                  ),
                ]),
              )),
        );
      }),
    );
  }
}
